
navigator.getMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMeddia || navigator.msGetUserMedia
const peer = new RTCPeerConnection({
    iceServers: [
        { urls: 'stun:stun.l.google.com:19302' },
        { urls: 'stun:global.stun.twilio.com:3478?transport=udp' }
    ]
})
let userName
let offerSDP
let answerSDP

const loginBtn = document.getElementById('loginBtn')
const messageList = document.getElementById('messageList')
const onlineUserSlt = document.getElementById('onlineUserSlt')
const callBtn = document.getElementById('callBtn')
const sendBtn = document.getElementById('sendBtn')
const videoPlayer = document.getElementById('videoPlayer')

loginBtn.onclick = function () {
    // 获取姓名
    userName = usernameInp.value

    // 建立连接
    socket = io.connect('http://127.0.0.1:80')

    // 设置连接成功回调函数
    socket.on('connect', function (data) {

        // 发送姓名给服务器
        socket.emit('new user', userName)

        // 显示聊天窗口
        chatAreaDiv.style.display = 'block'

        // 获得当前在线人员
        socket.on("online users", function (data) {
            onlineUsers = data
            console.log('当前在线用户:', data)
            let onlineUserSltIH = ''
            onlineUsers.forEach(el => {
                onlineUserSltIH += `<option value="${el}">${el}</option>`
            })
            onlineUserSlt.innerHTML = onlineUserSltIH
        })

        //接收聊天信息
        socket.on('to' + userName, function (data) {
            const li = document.createElement('Li')
            li.innerText = `${data.from}给你发消息: ${data.msg}`
            messageList.append(li)
            console.log(`${data.from}给你发消息: ${data.msg}`)
        })

        // 接收offer
        socket.on('accept offer', function (from, offerSDP) {
            console.log(`接收 ${from}的 offer:`, offerSDP)
            peer.setRemoteDescription(offerSDP)

            // 打开麦克风
            navigator.getMedia({
                // video: true, // 使用视频
                audio: true, // 使用音频
            }, async function(stream) {
                const audioStreamTrack = stream.getTracks()[0] // 获取音频轨
                // const mediaStreamTrack = stream.getTracks()[1] // 获取视频轨
                peer.addTrack(audioStreamTrack)

                // 创建,并发送Answer
                answerSDP = await peer.createAnswer()
                peer.setLocalDescription(answerSDP)
    
                socket.emit('answer offer', userName, from, answerSDP)
                
            }, function (err) {
                console.log(err)
            })
        })

        // 接收answer
        socket.on('accept answer', async function (from, answerSDP) {
            console.log(`接收 ${from}的 answer:`, answerSDP)
            peer.setRemoteDescription(answerSDP)
            // offerSDP = await peer.createOffer()
            // peer.setLocalDescription(offerSDP)
            // socket.emit('again offer', userName, from, offerSDP)
        })

        // 再次接收offer
        socket.on('again accept offer', async function (from, offerSDP) {
            console.log(`再次接收 ${from}的 offer:`, offerSDP)
            peer.setRemoteDescription(offerSDP)
            // answerSDP = await peer.createAnswer()
            // peer.setLocalDescription(answerSDP)
            socket.emit('again answer offer', userName, from, answerSDP)
        })

        // 再次接收answer
        socket.on('again accept answer', function (from, answerSDP) {
            console.log(`再次接收 ${from}的 answer:`, answerSDP)
            peer.setRemoteDescription(answerSDP)
        })

        // // 接收candidate
        // socket.on('accept candidate', function (from, candidate) {
        //     console.log(`接收 ${from}的 candidate:`, candidate)
        //     peer.addIceCandidate(candidate)
    })

    // // 数据收集
    // peer.onicecandidate = (e) => {
    //     const { candidate } = e
    //     peer.candidate = candidate
    //     socket.emit('new candidate', userName, 'user2', candidate)
    // }

    // 接收到媒体轨道的 callback
    peer.ontrack = (e) => {
        const { track } = e
        const video = videoPlayer
        const stream = new MediaStream()
        stream.addTrack(track)
        console.log(`接收到的轨道:`, track)

        try {
            video.srcObject = stream
        } catch (e) {
            console.log(e)
            video.src = (window.URL || window.webkitURL).createObjectURL(stream)
        }
    }
}

// 发送消息
sendBtn.onclick = function (e) {
    const msg = messageInp.value
    const to = onlineUserSlt.value
    socket.emit('private message', userName, to, msg)
}

// 发起通话
callBtn.onclick = function (e) {
    navigator.getMedia({
        // video: true, // 使用视频
        audio: true, // 使用音频
    }, async function(stream) {
        const audioStreamTrack = stream.getTracks()[0] // 获取音频轨
        // const mediaStreamTrack = stream.getTracks()[1] // 获取视频轨

        // 创建,并发送Offer
        peer.addTrack(audioStreamTrack)
        offerSDP = await peer.createOffer()
        peer.setLocalDescription(offerSDP)
        socket.emit('new offer', userName, onlineUserSlt.value, offerSDP)
        
    }, function (err) {
        console.log(err)
    })
}
